package cn.falcon.fmobi.console.controller;

import cn.falcon.fmobi.admin.dao.dao.model.ResultSetList;
import cn.falcon.fmobi.admin.dao.dao.model.UserDetailModel;
import cn.falcon.fmobi.admin.dao.dao.model.UserListModel;
import cn.falcon.fmobi.admin.entity.ShiroUser;
import cn.falcon.fmobi.admin.service.IUserRoleService;
import cn.falcon.fmobi.biz.service.AgentService;
import cn.falcon.fmobi.biz.service.CustomerService;
import cn.falcon.fmobi.biz.vo.DomainUser;
import cn.falcon.fmobi.biz.vo.FmobiUser;
import cn.falcon.fmobi.console.common.RestfulJsonModelAndView;
import cn.falcon.fmobi.console.common.Result;
import cn.falcon.fmobi.console.constant.UrlConstant;
import cn.falcon.fmobi.console.constant.UserRolePermission;
import cn.falcon.fmobi.console.requestparam.AccountQuery;
import cn.falcon.fmobi.console.requestparam.PasswordModel;
import cn.falcon.fmobi.console.requestparam.UserParam;
import cn.falcon.fmobi.console.response.UserPermissionInfo;
import cn.falcon.fmobi.dao.interceptor.PageParameter;
import cn.falcon.fmobi.dao.model.TreeVo;
import cn.falcon.fmobi.dao.po.Advertiser;
import cn.falcon.fmobi.dao.po.Agent;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import javax.security.auth.login.AccountException;
import javax.servlet.http.HttpSession;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;


@Controller
@RequestMapping(UrlConstant.USER_URL)
public class UserCtrl extends BaseCtrl{

	@Autowired
	private IUserRoleService userRoleService;

	@Autowired
	private CustomerService customerService;
	
	@Autowired
	private AgentService AgentService;
	
	//TODO 输入check需要详细，异常需要详细。
	/**
	 * 新增用户 <br/>
	 * url:api/user/{id}/create <br/>
	 *  HTTP请求方式： POST <br/>
	 * data:{ "name":"广告主名称", "password":"密码", "status":"状态", "roleId":1001,
	 * "advertiseId":9 }
	 * @return 成功返回：{"ret":200}
	 * @throws AccountException
	 */
	@RequestMapping(method = RequestMethod.POST)
	public ModelAndView createUser(@RequestBody UserParam userParam,HttpSession session) throws AccountException{
		int id = readSession(session).getId();
		
		UserDetailModel model = new UserDetailModel();
		model.setName(userParam.getName());
		model.setId(id);
		model.setPassword(userParam.getPassword());
		model.setStatus(userParam.getStatus());
		// 当为平台运营权限时。
		if (hasRole(UserRolePermission.USER_ROLE_PLATFORM)) {
			model.setCurrentUserRole(UserRolePermission.USER_ROLE_PLATFORM);
			model.setTeamId(userParam.getActorId());
			model.setRoleId(UserRolePermission.USER_ROLE_AGENT_ID);
		} else if (hasRole(UserRolePermission.USER_ROLE_AGENT)){// 当为代理商权限时。
				model.setCurrentUserRole(UserRolePermission.USER_ROLE_AGENT);
				if (userParam.getActorId()==0) {
					//当新建代理商时。TeamId 为 当前用户
					model.setTeamId(id);
				}else{
					model.setTeamId(userParam.getActorId());
				}
				if(StringUtils.equals(userParam.getUserrole(), UserRolePermission.USER_ROLE_AGENT)){
					model.setRoleId(UserRolePermission.USER_ROLE_AGENT_ID);
				}else{
					model.setRoleId(UserRolePermission.USER_ROLE_ADVERTISER_ID);
				}
		}else{
			throw new AccountException("没有用户管理权限！");
		}
		userRoleService.createUser(model);
		
		return RestfulJsonModelAndView.buildJsonModelAndView();
	}

	/**
	 * 根据现有业务只会修改密码和状态。
	 * @return 成功返回：{"ret":200}
	 * @throws AccountException
	 */
	@RequestMapping(method = RequestMethod.PUT)
	public ModelAndView editUser(@RequestBody UserParam userParam,HttpSession session) throws AccountException {
		int id = readSession(session).getId();
		//回传的model
		UserListModel updateModel = new UserListModel();
		updateModel.setId(userParam.getId());
		updateModel.setActorId(userParam.getActorId());
		updateModel.setName(userParam.getName());
		updateModel.setRole(userParam.getUserrole());
		updateModel.setStatus(userParam.getStatus());
		
		//更新的model
		UserDetailModel model = new UserDetailModel();
		model.setId(userParam.getId());
		model.setName(userParam.getName());
		if (StringUtils.isNotEmpty(userParam.getPassword())) {
			model.setPassword(userParam.getPassword());
		}
		
		model.setStatus(userParam.getStatus());
		// 当为平台运营权限时。
		if (hasRole(UserRolePermission.USER_ROLE_PLATFORM)) {
			updateModel.setRole(UserRolePermission.USER_ROLE_AGENT);
			updateModel.setRoleName("代理商");
			model.setRoleId(UserRolePermission.USER_ROLE_AGENT_ID);
			model.setTeamId(userParam.getActorId());
		} else if (hasRole(UserRolePermission.USER_ROLE_AGENT)) {
			if (StringUtils.equals(userParam.getUserrole(), UserRolePermission.USER_ROLE_AGENT)) {
				updateModel.setRoleName("代理商");
				model.setRoleId(UserRolePermission.USER_ROLE_AGENT_ID);
			} else {
				updateModel.setRoleName("广告主");
				model.setRoleId(UserRolePermission.USER_ROLE_ADVERTISER_ID);
			}
			if (userParam.getActorId() == 0) {
				// 当新建代理商时。TeamId 为 当前用户
				model.setTeamId(id);
			} else {
				model.setTeamId(userParam.getActorId());
			}
		} else {
			throw new AccountException("没有用户管理权限！");
		}
		
		//更新
		userRoleService.updateUser(model);
		userListModelResize(updateModel);
		return RestfulJsonModelAndView.buildJsonModelAndView(updateModel);
	}
	
	/**
	 * 修改当前登录账户的密码
	 * @param params
	 * @return
	 * @throws AccountException
	 */
	@RequestMapping(method = RequestMethod.PUT,value="password")
	public ModelAndView modifiedPassword(@RequestBody PasswordModel params) throws AccountException {
		//获取当前登录用户ID
		ShiroUser shiroUser = getCurrentUser();
		if(!params.getRepeatPassword().equals(params.getPassword())){
			throw new AccountException("两次输入的密码不一致");
		}
		//与原密码是否一致
		if(shiroUser.getPassword().equals(DigestUtils.md5DigestAsHex(params.getOldPassword().getBytes()))){
			//密码一致。可以进行修改密码
			userRoleService.updatePassword(shiroUser.getId(),params.getPassword());
			shiroUser.setPassword(DigestUtils.md5DigestAsHex(params.getPassword().getBytes()));
			
		}else{
			throw new AccountException("原密码输入不正确！");
		}
		return RestfulJsonModelAndView.buildJsonModelAndView();
	}
	
	/**
	 * 查询单个用户信息
	 * @param id
	 * @return
	 */
	@RequestMapping(method = RequestMethod.GET,value="{id}")
	public ModelAndView read( @PathVariable("id") Integer id){
		return RestfulJsonModelAndView.buildJsonModelAndView("sss");
	}
	
	/**
	 * 查询用户列表
	 * @return
	 */
	@RequestMapping(method = RequestMethod.GET)
	public ModelAndView getUserList(AccountQuery query, HttpSession session){
		Map<String,Object> map = query.getSearchMap();
		//代理商查询，代理商商下的用户。 及广告主的账户
		//运营查询所有用户
		Integer AgentId = getLoginUser(session)!=null?getLoginUser(session).getAgentId():null;
		
		if(hasRole(UserRolePermission.USER_ROLE_PLATFORM)){
			map.put("operativer", 1);
		}
		if(AgentId!=null){
			map.put("agentId", AgentId);
			//查询代理商下广告主列表
			List<TreeVo> adverList = customerService.listAdvertiserByAgencyId(AgentId);
			StringBuilder sb = new StringBuilder();
			
			if(adverList!=null&&adverList.size()>0){
				for (TreeVo dropDownModel : adverList) {
					sb.append(dropDownModel.getId()).append(",");
				}
				sb.deleteCharAt(sb.length()-1);
				map.put("advertiserIds", sb.toString());
			}
		}
		PageParameter page = query.getPageInfo();
		ResultSetList<UserListModel> list = userRoleService.selectUserList(map,page.getCurrentPage(),page.getPageSize());
		
		List<UserListModel> adList = list.getList();
		for (UserListModel userListModel : adList) {
			userListModelResize(userListModel);
		}
		return RestfulJsonModelAndView.buildJsonModelAndView(list);
	}

	/**
	 * 重新组合UserListModel对象
	 * @param userListModel
     */
	private void userListModelResize(UserListModel userListModel) {
		if(userListModel.getRole().equals(UserRolePermission.USER_ROLE_ADVERTISER)){
            Advertiser advertiser = customerService.getAdvertiserById(userListModel.getActorId());
            userListModel.setUserName(advertiser==null?"":advertiser.getCompanyName());
        }else if(userListModel.getRole().equals(UserRolePermission.USER_ROLE_AGENT)){
            Agent Agent = AgentService.getAgentById(userListModel.getActorId());
            userListModel.setUserName(Agent==null?"":Agent.getName());
        }
	}



	/**
	 * 获取当前登录用户的信息包括角色和权限信息
	 * @return
	 */
	@RequestMapping(method = RequestMethod.GET, value = "login")
	public ModelAndView loginUserInfo(HttpSession session) {
		FmobiUser user = readSession(session);
		DomainUser domainUser = getLoginUser(session);
		List<String> permissions = null;
		UserPermissionInfo info = new UserPermissionInfo();
		if(StringUtils.equals(UserRolePermission.USER_ROLE_AGENT,user.getRole())){
			permissions = userRoleService.selectRolePermission(UserRolePermission.USER_ROLE_AGENT_ID);
		}else if(StringUtils.equals(UserRolePermission.USER_ROLE_ADVERTISER,user.getRole())){
			permissions = userRoleService.selectRolePermission(UserRolePermission.USER_ROLE_ADVERTISER_ID);
		}else if(StringUtils.equals(UserRolePermission.USER_ROLE_ADVERTISER,user.getRole())){
			permissions = userRoleService.selectRolePermission(UserRolePermission.USER_ROLE_ADVERTISER_ID);
		}else if(StringUtils.equals(UserRolePermission.USER_ROLE_PLATFORM,user.getRole())){
			permissions = userRoleService.selectRolePermission(UserRolePermission.USER_ROLE_PLATFORM_ID);
		}
		info.setRole(user.getRole());
		info.setPermissions(permissions);
		info.setName(domainUser.getName());
		return RestfulJsonModelAndView.buildJsonModelAndView(info);
	}

	/**
	 * 验证用户是否有permission 权限
	 * @param permission
	 * @return
	 */
	@RequestMapping(method = RequestMethod.GET, value = "hasPermission")
	public ModelAndView hasPermission(String resource, String permission,HttpSession session) {
		if (org.springframework.util.StringUtils.isEmpty(permission) || org.springframework.util.StringUtils.isEmpty(resource)) {
			return RestfulJsonModelAndView.buildError(Result.ERR_MISS_PARAMETER, "缺少请求参数或者请求参数值为空", "");
		}
		List<String> permissions = null;
		FmobiUser user = readSession(session);
		if(StringUtils.equals(UserRolePermission.USER_ROLE_AGENT,user.getRole())){
			permissions = userRoleService.selectRolePermission(UserRolePermission.USER_ROLE_AGENT_ID);
		}else if(StringUtils.equals(UserRolePermission.USER_ROLE_ADVERTISER,user.getRole())){
			permissions = userRoleService.selectRolePermission(UserRolePermission.USER_ROLE_ADVERTISER_ID);
		}else if(StringUtils.equals(UserRolePermission.USER_ROLE_PLATFORM,user.getRole())){
			permissions = userRoleService.selectRolePermission(UserRolePermission.USER_ROLE_PLATFORM_ID);
		}
		String p = resource + ":" + permission;
		String res = p + ":total";
		Set<String> result = new HashSet<>();
		if (permissions.contains(res)) {
			result.add(res);
		} else {
			for (String str : permissions) {
				if (str.substring(0,str.lastIndexOf(":")).equals(p)) {
					result.add(str);
				}
			}
		}
		return RestfulJsonModelAndView.buildJsonModelAndView(result);
	}

}
